'use strict';

const crypto = require('crypto');
// const BASE_URL = 'https://yunzhuan.zgwlkj.cn/api-admin'
const BASE_URL = 'http://ceshi.zgwlkj.cn:10081'
const db = uniCloud.database();

const DEFAUTL_TIMEOUT = 30000;
const DEFAUTL_RETRY_COUNT = 3;
const RETRY_TIMEOUT = 3000;

const ProviderType = {
  CSJ: "csj",
  GDT: "gdt",
  KS: "ks"
};

const collectionName = "opendb-uniad-callback-log";

class DB {

  static save(data) {
    return new DB().add(data);
  }

  add(data) {
    const collection = db.collection(collectionName);
    const data2 = Object.assign(data, {
      ad_type: 0,
      create_date: new Date()
    })
    return collection.add(data2);
  }
}

class UserServer {

  static send(url, data) {
    return new UserServer().sendHttpRequest(url, data);
  }

  async sendHttpRequest(url, data) {
    let needRetry = data.provider !== ProviderType.GDT;
    let retryCount = needRetry ? DEFAUTL_RETRY_COUNT : 1;
    let timeout = needRetry ? RETRY_TIMEOUT : DEFAUTL_TIMEOUT;
    let result = null;

    while (retryCount > 0) {
      console.log("sendHttpRequest::count::" + retryCount + "::", url, data);
		
      try {
        result = await uniCloud.httpclient.request(url, {
		  method: 'POST',
          data,
		  headers:{
			  Authorization:data.toKen
		  },
          dataType: 'json',
          contentType: 'json',
          timeout
        });

        if (result) {
			
			console.log("请求个人信息",result.data)
          break;
        }
      } catch (e) {
        console.log(e);
      }

      retryCount--;
    }

    return result;
  }
}

exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event);
  console.log('context来源:', context.SOURCE );
  const {
    path,
    queryStringParameters
  } = event;

  const data = {
	adpid: event.adpid,
	platform: event.platform,
	provider: event.provider,
	transId: event.transId,
	sign: event.sign,
	extra: event.extra,
    toKen:event.toKen,
	open:event.time,
	imei:event.imei
  }
  
  let toKen = event.toKen
  // 注意::必须验签请求来源
  const secret = "APPid-zg";// uniad 后台开通激励视频回调后生成的 secret
  const transId = data.transId;
  const sign2 = crypto.createHmac('sha256',Buffer.from(`${secret}`, 'utf8')).update(Buffer.from(`${transId}`, 'utf8')).digest().toString('base64');
  console.log("transId",transId)
  if (event.sign !== sign2) {
    return {
		"isValid": false,
		"message":"领取失败"
	  };
  }


  // 可选将回调记录保存到uniCloud，避免用户服务器没有响应时有日志可查，如果选择了保存记录需要做定时清理日志，避免日志过多影响性能
  // try {
  //   await DB.save(data);
  // } catch (e) {
  //   console.log(e);
  // }

  const url = BASE_URL+"/adcpd/saveAdcpa"; // 用户业务服务器地址，为了避免请求被伪造，必须使用签名的方式请求
  const {
  	data: {
  		code,
  		message
  	}
  } = await UserServer.send(url, data);
  return {
    "isValid": code ==200?true:false,
  	"message":message
  }
};